package it.sources.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import it.sources.blog.domain.ArticleType;
import it.sources.blog.domain.query.ArticleTypeQuery;
import it.sources.blog.mapper.ArticleTypeMapper;
import it.sources.blog.service.IArticleTypeService;
import it.sources.untile.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@CacheConfig(cacheNames = "articleType")
public class ArticleTypeServiceImpl implements IArticleTypeService {
    @Autowired
    private ArticleTypeMapper ump;
    @Override
    public List<ArticleType> findAll() {
        return ump.findAll();
    }

    @Override
    public ArticleType findOne(Long id) {
        return ump.findOne(id);
    }
@CacheEvict(key = "typeTree")
    @Override
    public void delet(Long id) {
        ump.delet(id);
    }

    @CacheEvict(key = "typeTree")
    @Override
    public void upDate(ArticleType articleType) {
        ump.upDate(articleType);
    }
    @CacheEvict(key = "typeTree")
    @Override
    public void add(ArticleType articleType) {
        ump.add(articleType);
    }

    @CacheEvict(key = "typeTree")
    @Override
    public R pathDele(Long[] id) {
        ump.pathDele(id);
        return R.success();
    }

    @Override
    public PageInfo<ArticleType> queryPage(ArticleTypeQuery articleTypeQuery) {
        PageHelper.startPage(articleTypeQuery.getCurrentPage(), articleTypeQuery.getPageSize());
        List<ArticleType> articleTypes = ump.queryPage(articleTypeQuery);
        PageInfo<ArticleType> info = new PageInfo<ArticleType>(articleTypes);
        return  info;
    }
@Cacheable(key = "typeTree")
    @Override
    public List<ArticleType> typeTree() {
        return gettypeTree();
    }


    public List<ArticleType> gettypeTree() {
        List<ArticleType> types = new ArrayList<ArticleType>();
        List<ArticleType> all = ump.findAll();
        HashMap<Long, ArticleType> map = new HashMap<>();
        for (ArticleType type : all) {
            map.put(type.getId(),type);
        }
        for (ArticleType articleType : all) {
            if(articleType.getParentId()==null){
                types.add(articleType);
            }else {
                Long parentId = articleType.getParentId();
                ArticleType ptype = map.get(parentId);
                if (ptype!=null){
                    ptype.getChildren().add(articleType);
                }
            }
        }
        return types;
    }

}
